package com.chwn.curiousdiary.ui.register;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.CardView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chwn.curiousdiary.DiaryApplication;
import com.chwn.curiousdiary.ui.main.MainActivity;
import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.api.IUserApi;
import com.chwn.curiousdiary.api.NetWork;
import com.chwn.curiousdiary.bean.RegisterBean;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.gloable.User;
import com.chwn.curiousdiary.utils.CustomToast;
import com.chwn.curiousdiary.utils.DialogUtil;
import com.chwn.harulib.base.BaseActivity;
import com.chwn.harulib.mvp.rx.HttpResult;
import com.chwn.harulib.util.RegexValidateUtil;
import com.chwn.harulib.util.ToastUtil;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Description: 由于注册、绑定手机、忘记密码的界面与数据交互大致一致，因此将其写在一个Activity.
 * 命名仍用RegisterActivity
 * 使用传入的Intent中包含的PageType进行区别
 * Copyright  : Copyright (c) 2016
 * Company    :
 * Author     :
 * Date       : 2017/3/26 17:22
 */

public class RegisterActivity extends BaseActivity {

    @BindView(R.id.tv_page_title)
    TextView     mPageTitle;
    @BindView(R.id.et_user_phone)
    EditText     mUserPhoneET;
    @BindView(R.id.et_user_code)
    EditText     mUserCodeET;
    @BindView(R.id.tv_code)
    TextView     mCodeTV;
    @BindView(R.id.et_user_pwd)
    EditText     mUserPwdET;
    @BindView(R.id.ib_pwd_visible)
    ImageButton  mPwdVisibleIB;
    @BindView(R.id.ib_register)
    CardView     mRegisterIB;
    @BindView(R.id.tv_btn_text)
    TextView     mBtnText;
    @BindView(R.id.iv_end_action)
    ImageView    mLoginIV;
    @BindView(R.id.tv_end_action)
    TextView     mLoginTV;
    @BindView(R.id.tv_text)
    TextView     mText;
    @BindView(R.id.ll_pwd_input)
    LinearLayout mPwdInput;

    private int      mPageType;
    private IUserApi apiService;
    private String   unionid;
    private String   phone;
    private int      verifyType;

    private boolean isBindRegistedPhone = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);  //全屏
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }

    @Override
    protected void initData() {
        super.initData();
        mPageType = getIntent().getIntExtra(Constant.JUMP_TYPE, Constant.FGT_PWD);
        unionid = getIntent().getStringExtra(Constant.UNION_ID);
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        switch (mPageType) {
            case Constant.FGT_PWD:
                mText.setText("完成");
                mLoginTV.setText("提交");
                mPageTitle.setText("忘记密码");
                break;
            case Constant.BIND_PHONE:
                mText.setText("绑定");
                mLoginTV.setText("绑定");
                mPageTitle.setText("绑定手机");
                mPwdInput.setVisibility(View.GONE);
                break;
            case Constant.REGISTER:
                mText.setText("注册");
                mLoginTV.setText("完成");
                mPageTitle.setText("注册");
                break;
        }
        //        mUserPwdET.setTransformationMethod(PasswordTransformationMethod.getInstance());
        //        mLoginIV.setAlpha(90);
        mLoginTV.setAlpha(0.6f);
        mUserCodeET.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        mLoginTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                checkInput();
            }
        });

    }

    @Override
    protected void initListener() {
        super.initListener();
        mUserPhoneET.addTextChangedListener(watcher);
        mUserCodeET.addTextChangedListener(watcher);
        mUserPwdET.addTextChangedListener(watcher);
    }

    @Override
    protected boolean isRequireCustomAnim() {
        return true;
    }

    @OnClick({R.id.ib_back, R.id.tv_code, R.id.ib_pwd_visible, R.id.ib_register, R.id.tv_end_action})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_back://返回
                finish();
                break;
            case R.id.tv_code: //发送验证码
                String phone = mUserPhoneET.getText().toString().trim();
                if (TextUtils.isEmpty(phone)) {
                    ToastUtil.shortShowToast("请输入手机号");
                    return;
                } else if (!RegexValidateUtil.checkCellphone(phone)) {
                    ToastUtil.shortShowToast("请输入正确的手机号");
                    return;
                }
                sendVerifyCode(phone);
                break;
            case R.id.ib_pwd_visible://显示密码
                boolean selected = mPwdVisibleIB.isSelected();
                if (selected) {//不可见
                    mPwdVisibleIB.setSelected(false);
                    mUserPwdET.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {//可见
                    mPwdVisibleIB.setSelected(true);
                    mUserPwdET.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
                break;
            case R.id.ib_register://最后操作
                checkInput();
                break;
            case R.id.iv_end_action:

                break;
        }
    }

    TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            String phone = mUserPhoneET.getText().toString().trim();
            String passWord = mUserPwdET.getText().toString().trim();
            String code = mUserCodeET.getText().toString().trim();
            if (!TextUtils.isEmpty(phone)
                    && RegexValidateUtil.checkCellphone(phone)
                    && !TextUtils.isEmpty(code)
                    && code.length() == 4) {
                if (isBindRegistedPhone) {
                    //                    mLoginIV.setAlpha(Integer.MAX_VALUE);
                    mLoginTV.setAlpha(1.0f);

                } else if (!TextUtils.isEmpty(passWord)
                        && passWord.length() > Constant.MIN_NUM_PWD - 1
                        && passWord.length() < Constant.MAX_NUM_PWD + 1) {
                    //                    mLoginIV.setAlpha(Integer.MAX_VALUE);
                    mLoginTV.setAlpha(1.0f);
                }

            } else {
                //                mLoginIV.setAlpha(90);
                mLoginTV.setAlpha(0.6f);
            }
        }


        @Override
        public void afterTextChanged(Editable editable) {

        }
    };

    private void checkInput() {
        phone = mUserPhoneET.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            ToastUtil.shortShowToast("请输入手机号");
            return;
        } else if (!RegexValidateUtil.checkCellphone(phone)) {
            ToastUtil.shortShowToast("请输入正确的手机号");
            return;
        }
        String smsCode = mUserCodeET.getText().toString().trim();
        if (TextUtils.isEmpty(smsCode)) {
            ToastUtil.shortShowToast("请输入验证码");
            return;
        }

        if (smsCode.length() != 4) {
            ToastUtil.shortShowToast("请确认验证码个数");
            return;
        }

        String passWord = mUserPwdET.getText().toString();
        if (!isBindRegistedPhone) {
            if (TextUtils.isEmpty(passWord)) {
                ToastUtil.shortShowToast("请输入密码");
                return;
            } else if (passWord.length() < Constant.MIN_NUM_PWD || passWord.length() > Constant.MAX_NUM_PWD) {
                ToastUtil.shortShowToast("请输入6-18英文或数字密码");
                return;
            }
        }
        endAction(phone, smsCode, passWord);
    }

    /**
     *
     */
    private Observer<HttpResult<List<User>>> mObserver = new Observer<HttpResult<List<User>>>() {
        @Override
        public void onCompleted() {
            DialogUtil.dismissWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            //            errAction("");
            DialogUtil.dismissWaitDialog();
        }

        @Override
        public void onNext(HttpResult<List<User>> result) {
            DialogUtil.dismissWaitDialog();
            if (result.getResult() == Constant.RESULT_ERROR) { //失败
                errAction(result.getErrorMessage());
                return;
            }
            Intent resultIntent = getIntent();
            switch (mPageType) {
                case Constant.REGISTER: //返回登录界面

                    CustomToast.showShortToast("注册成功, 请登录");
                    resultIntent.putExtra(Constant.JUMP_TYPE, phone);
                    RegisterActivity.this.setResult(Constant.REGISTER, resultIntent);
                    finish();
                    break;
                case Constant.FGT_PWD: //返回登录界面
                    CustomToast.showShortToast("修改密码成功 , 请登录");
                    resultIntent.putExtra(Constant.JUMP_TYPE, phone);
                    RegisterActivity.this.setResult(Constant.FGT_PWD, resultIntent);
                    finish();
                    break;
                case Constant.BIND_PHONE: //进入宝宝信息选择界面  登录成功
                    List<User> resdata = result.getResdata();
                    User user = resdata.get(0);
                    DiaryApplication.mInstance.saveUser(user);
                    if (!TextUtils.isEmpty(user.getBabybirth())) {
                        startActivity(new Intent(RegisterActivity.this, MainActivity.class));
                    } else {
                        Intent intent = new Intent(RegisterActivity.this, BabyInfoActivity.class);
                        intent.putExtra(Constant.PHONE, phone);
                        intent.putExtra(Constant.UNION_ID, unionid);
                        startActivity(intent);
                    }
                    finish();
                    break;
            }
        }
    };

    private Observer<HttpResult<Object>> mFGTObserver = new Observer<HttpResult<Object>>() {
        @Override
        public void onCompleted() {
            DialogUtil.dismissWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            //            errAction("");
            DialogUtil.dismissWaitDialog();
        }

        @Override
        public void onNext(HttpResult<Object> result) {
            DialogUtil.dismissWaitDialog();
            if (result.getResult() == Constant.RESULT_ERROR) { //失败
                errAction(result.getErrorMessage());
                return;
            }
            Intent resultIntent = getIntent();
            switch (mPageType) {
                case Constant.REGISTER: //返回登录界面

                    CustomToast.showShortToast("注册成功, 请登录");
                    resultIntent.putExtra(Constant.JUMP_TYPE, phone);
                    RegisterActivity.this.setResult(Constant.REGISTER, resultIntent);
                    finish();
                    break;
                case Constant.FGT_PWD: //返回登录界面
                    CustomToast.showShortToast("修改密码成功 , 请登录");

                    resultIntent.putExtra(Constant.JUMP_TYPE, phone);
                    RegisterActivity.this.setResult(Constant.FGT_PWD, resultIntent);
                    finish();
                case Constant.BIND_PHONE: //进入宝宝信息选择界面  登录成功
                    User user = DiaryApplication.mInstance.getmUser();
                    user.setPhone(phone);
                    Intent intent = new Intent(RegisterActivity.this, BabyInfoActivity.class);
                    intent.putExtra(Constant.PHONE, phone);
                    startActivity(intent);
                    finish();
                    break;
            }

            finish();
        }
    };

    private Observer<HttpResult<List<User>>> mRegisterObserver = new Observer<HttpResult<List<User>>>() {
        @Override
        public void onCompleted() {
            DialogUtil.dismissWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            //            errAction("");
            DialogUtil.dismissWaitDialog();
        }

        @Override
        public void onNext(HttpResult<List<User>> result) {
            DialogUtil.dismissWaitDialog();
            if (result.getResult() == Constant.RESULT_ERROR) { //失败
                errAction(result.getErrorMessage());
                return;
            }
            Intent resultIntent = getIntent();
            switch (mPageType) {
                case Constant.REGISTER: //返回登录界面

                    CustomToast.showShortToast("注册成功, 请登录");
                    resultIntent.putExtra(Constant.JUMP_TYPE, phone);
                    RegisterActivity.this.setResult(Constant.REGISTER, resultIntent);
                    finish();
                    break;
                case Constant.FGT_PWD: //返回登录界面
                    CustomToast.showShortToast("修改密码成功 , 请登录");
                    resultIntent.putExtra(Constant.JUMP_TYPE, phone);
                    RegisterActivity.this.setResult(Constant.FGT_PWD, resultIntent);
                    finish();
                case Constant.BIND_PHONE: //进入宝宝信息选择界面  登录成功
                    User user = DiaryApplication.mInstance.getmUser();
                    user.setPhone(phone);
                    Intent intent = new Intent(RegisterActivity.this, BabyInfoActivity.class);
                    intent.putExtra(Constant.PHONE, phone);
                    startActivity(intent);
                    finish();
                    break;
            }

            finish();
        }
    };

    private void errAction(String errorMsg) {
        String text;
        if (TextUtils.isEmpty(errorMsg)) {
            text = "请检查网络链接";
        } else {
            text = errorMsg;
        }

        CustomToast.showShortToast(text);
    }

    /**
     * 最后操作
     * @param phone
     * @param smsCode
     * @param passWord
     */
    private void endAction(String phone, String smsCode, String passWord) {
        apiService = NetWork.getInstance()
                .getApiService(IUserApi.class);
        switch (mPageType) {
            case Constant.REGISTER:
                apiService
                        .userRegister(phone, passWord, Constant.OSTYPE, Integer.parseInt(smsCode))
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Action0() {
                            @Override
                            public void call() {
                                showWaitDialog("请稍等...");
                            }
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(mRegisterObserver);
                break;
            case Constant.FGT_PWD:
                apiService
                        .editUserPassword(phone, passWord, Constant.OSTYPE, Integer.parseInt(smsCode))
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Action0() {
                            @Override
                            public void call() {
                                showWaitDialog("请稍等...");
                            }
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(mFGTObserver);
                break;
            case Constant.BIND_PHONE:
                apiService
                        .userBindPhone(phone, passWord, unionid, Constant.OSTYPE, Integer.parseInt(smsCode))
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(new Action0() {
                            @Override
                            public void call() {
                                showWaitDialog("请稍等...");
                            }
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(mObserver);
                break;
        }
    }

    /**
     * 发送验证码
     */
    private void sendVerifyCode(String phone) {
        verifyType = 1;
        switch (mPageType) {
            case Constant.FGT_PWD:
                verifyType = 3;
                break;
            case Constant.BIND_PHONE:
                verifyType = 2;
                break;
            case Constant.REGISTER:
                verifyType = 1;
                break;
        }
        apiService = NetWork.getInstance()
                .getApiService(IUserApi.class);

        apiService
                .sendSms(phone, Constant.OSTYPE, verifyType, unionid)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        showWaitDialog("发送中...");
                    }
                })
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<HttpResult<List<RegisterBean>>>() {
                    @Override
                    public void onCompleted() {
                        DialogUtil.dismissWaitDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        DialogUtil.dismissWaitDialog();
                        CustomToast.showShortToast("发送验证码失败");
                    }

                    @Override
                    public void onNext(HttpResult<List<RegisterBean>> userHttpResult) {
                        DialogUtil.dismissWaitDialog();
                        if (userHttpResult.getResult() == Constant.RESULT_ERROR) {
                            switch (mPageType) {
                                case Constant.FGT_PWD:
                                    CustomToast.showShortToast(userHttpResult.getErrorMessage());
                                    break;
                                case Constant.BIND_PHONE:
                                    CustomToast.showShortToast(userHttpResult.getErrorMessage());
                                    String isRegister = userHttpResult.getResdata().get(0).getIsRegister();

                                    if ("1".equals(isRegister)) {
                                        isBindRegistedPhone = true;
                                        mPwdInput.setVisibility(View.GONE);
                                    } else {
                                        isBindRegistedPhone = false;
                                        mPwdInput.setVisibility(View.VISIBLE);
                                    }
                                    break;
                                case Constant.REGISTER:

                                    if ("该手机已被注册，请更换手机号".equals(userHttpResult.getErrorMessage())) {
                                        CustomToast.showShortToast("此账号已注册 请直接登录");
                                        finish();
                                    } else {
                                        CustomToast.showShortToast(userHttpResult.getErrorMessage());
                                    }
                                    break;
                            }

                            return;
                        } else {

                            //                            ToastUtil.shortShowToast(userHttpResult.getResdata().get(0).getNumber());

                            if (mPageType == Constant.BIND_PHONE) {
                                String isRegister = userHttpResult.getResdata().get(0).getIsRegister();

                                if ("1".equals(isRegister)) {
                                    isBindRegistedPhone = true;
                                    mPwdInput.setVisibility(View.GONE);
                                } else {
                                    isBindRegistedPhone = false;
                                    mPwdInput.setVisibility(View.VISIBLE);
                                }
                            }

                            Timer timer = new Timer();
                            timer.schedule(new Task(0), 0L, 1000L);
                            mCodeTV.setEnabled(false);
                            mCodeTV.setTextColor(getResources().getColor(R.color.verify_code));
                            mCodeTV.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_verify_code_bg));
                        }
                    }
                });

    }

    /**
     * 验证码重新发送时间设置
     */
    private class Task extends TimerTask {
        private int time = 90;
        private int tag;

        public Task(int tag) {
            this.tag = tag;
        }

        @Override
        public void run() {
            Message message = handler.obtainMessage();
            message.what = tag;
            message.arg1 = time;
            handler.sendMessage(message);
            time--;
            if (time < 0) {
                cancel();
            }
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    if (mCodeTV == null)
                        return;
                    mCodeTV.setText(msg.arg1 + "秒");
                    if (msg.arg1 == 0) {
                        int color = getResources().getColor(R.color.send_verify_code);
                        mCodeTV.setText("发送验证码");
                        mCodeTV.setEnabled(true);
                        mCodeTV.setTextColor(color);
                        mCodeTV.setBackgroundDrawable(getResources().getDrawable(R.drawable.shape_fgt_pwd_bg));
                    }
                    break;
            }

        }
    };

    void showWaitDialog(String text) {
        DialogUtil.showWaitDialog(RegisterActivity.this, text, false);
    }
}
